//
//  LocationViewController.m
//  跳转第三方地图
//
//  Created by apple on 2017/8/18.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "LocationViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <StoreKit/StoreKit.h>
#import <MapKit/MapKit.h>
@interface LocationViewController ()<CLLocationManagerDelegate>{
    
    NSString *currentCity;
}

@property (nonatomic, strong) CLLocationManager *locationManager;


@property (nonatomic, assign) BOOL isYESBD;
@property (nonatomic, assign) BOOL isYESGD;
@property (nonatomic, assign) BOOL isYESGG;

@property (nonatomic, strong) NSMutableArray *availableMaps;

@property (nonatomic, assign) float laiFloat;
@property (nonatomic, assign) float lonFloat;

@property (nonatomic, assign) int l;

//@property (nonatomic, strong)

@end

@implementation LocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(100, 400, 100, 50)];
    
    [btn setTitle:@"进入" forState:UIControlStateNormal];
    
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:btn];
    
    self.l = 0;
    
    [self startLocation];
    
    [self availableMapsApps];
    
    [self createDiLiCode];
}

#pragma 获取自己位置 - 跳转第三方地图时，会自动获取
//开始定位
- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        //        CLog(@"--------开始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        //控制定位精度
        self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
        // 总是授权
        [self.locationManager requestAlwaysAuthorization];
        self.locationManager.distanceFilter = 10.0f;
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}

#pragma 获取自己位置失败时调用的方法
//请求失败的时候
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}

#pragma 获取自己位置 - 不断更新
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    //    CLLocation *newLocation = locations[0];
    CLLocation *newLocation = locations.lastObject;
    
    //获取经纬度
    CLLocationCoordinate2D gps = CLLocationCoordinate2DMake(locations.lastObject.coordinate.latitude, locations.lastObject.coordinate.longitude);
    
//    self.laiFloat = gps.latitude;
//    self.lonFloat = gps.longitude;
    
//    NSLog(@"gps = %f",gps.latitude);
//    NSLog(@"gps = %f",gps.longitude);
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            //            CLPlacemark *placemark = [array objectAtIndex:0];
            CLPlacemark *placemark = array.lastObject;
            //            NSLog(@"array = %@",array);
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            NSLog(@"city = %@", city);//杭州市
            NSLog(@"--%@",placemark.name);//十二号路
            NSLog(@"++++%@",placemark.subLocality); //富阳区
            NSLog(@"country == %@",placemark.country);//中国
            NSLog(@"administrativeArea == %@",placemark.administrativeArea); //浙江省
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    
#pragma 关闭一直更新位置
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
    
   
    
}

//地理编码获取经纬度
- (void)createDiLiCode{
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    NSString *address = @"安徽省六安市裕安区皖西学院";
    
    // 容错
    if([address length] == 0)
        return;
    
    [geocoder geocodeAddressString:address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        // CLPlacemark : 地标
        // location : 位置对象
        // addressDictionary : 地址字典
        // name : 地址详情
        // locality : 城市
        
        if(error == nil)
        {
            CLPlacemark *pl = [placemarks firstObject];
            
            self.laiFloat = pl.location.coordinate.latitude;
            self.lonFloat = pl.location.coordinate.longitude;
            
            NSLog(@"_lai = %f",_laiFloat);
            NSLog(@"_lon = %f",_lonFloat);
        }else
        {
            NSLog(@"错误");
        }
    }];
    
}

//判断是否安装地图
- (void)availableMapsApps {
    [self.availableMaps removeAllObjects];
    
    //    NSLog(@"我是第几输出的啊！！");
    NSString *toName = @"to name";
    
    //百度
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://map/"]]){
        
        NSLog(@"我TM装了百度啊");

        
        self.isYESBD = YES;
        
    }
    //高德
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
   
        
        self.isYESGD = YES;
        
    }
}

//进入按钮点击事件
- (void)btnClick:(UIButton *)sender{
    
    [self createAlert];
}

//创建弹窗
- (void)createAlert{
    
    static NSString *appName = @"跳转第三方地图";
    static NSString *urlScheme = @"tzdsfdt";
    
    if (self.isYESBD == YES&&self.isYESGD == NO) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=北京&mode=driving&coord_type=gcj02",_laiFloat,_lonFloat] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        [action1 setValue:[UIColor redColor] forKey:@"_titleTextColor"];
        
        [alert addAction:action];
        [alert addAction:action1];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }else if (self.isYESGD == YES&&self.isYESBD == NO){
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",appName,urlScheme,_laiFloat,_lonFloat] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];
        
        [action1 setValue:[UIColor redColor] forKey:@"_titleTextColor"];
        
        [alert addAction:action];
        [alert addAction:action1];
        
        [self presentViewController:alert animated:YES completion:nil];
        
        
    }else if (self.isYESGD == YES&&self.isYESBD == YES){
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=不搭嘎&mode=driving&coord_type=gcj02",_laiFloat,_lonFloat] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"高德地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSString *urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",appName,urlScheme,_laiFloat,_lonFloat] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
            
        }];
        
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            
        }];

        [action3 setValue:[UIColor redColor] forKey:@"_titleTextColor"];
        
        [alert addAction:action1];
        [alert addAction:action2];
        [alert addAction:action3];
        
        [self presentViewController:alert animated:YES completion:nil];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
